<!--
 Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<!--

This file is used to help develop Host<->Guest communications.

Usage:

  1. In terminal 1: start the dev frontend server
     $ cd frontend
     $ yarn start

  2. In terminal 2: run your Streamlit app
     $ cd lib
     $ pipenv shell
     $ cd ..
     $ streamlit run foo.py

  3. In terminal 3: serve this file
     $ cd frontend
     $ python -m http.server

  ...then open localhost:8000 in a browser!

-->

<script>
  window.addEventListener("message", (event) => {
    console.log("Received message event:", event);

    if (event.data.type === "REDIRECT_TO_URL") {
      window.location.href = event.data.url
    }
  });

  function sendMessage(data) {
    const guestwindow = document.getElementById("guest").contentWindow;

    guestwindow.postMessage(
      {
        stCommVersion: 1,
        ...data,
      },
      "*"
    );
  }

  function setHostMenuItem() {
    sendMessage({
      type: "SET_MENU_ITEMS",
      items: [
        {
          type: "text",
          label: "Adopt a Corgi",
          key: "share",
        },
        {
          type: "separator",
        },
      ],
    });
  }

  function setHostToolbarItem() {
    sendMessage({
      type: "SET_TOOLBAR_ITEMS",
      items: [
        {
          borderless: false,
          label: "Favorite",
          icon: "Favorite",
          key: "favorite",
        },
        {
          borderless: false,
          label: "Share",
          icon: "Share",
          key: "Share",
        },
      ],
    });
  }

  function setHideSidebarNav() {
    sendMessage({
      type: "SET_SIDEBAR_NAV_VISIBILITY",
      hidden: true,
    });
  }

  function setSidebarDownshift() {
    sendMessage({
      type: "SET_SIDEBAR_CHEVRON_DOWNSHIFT",
      sidebarChevronDownshift: 50,
    });
  }

  function setAuthToken() {
    // We handle auth token and jwt header name/value in child iframe,
    // only when `useExternalAuthToken` is set to True in
    // "_stcore/host-config" endpoint. Otherwise, we ignore this message.
    sendMessage({
      type: "SET_AUTH_TOKEN",
      authToken: "AUTH_TOKEN",
      jwtHeaderName: "X-JWT-HEADER-NAME",
      jwtHeaderValue: "X-JWT-HEADER-VALUE",
    });
  }

  function setFileUploadClientConfig() {
    sendMessage({
      type: "SET_FILE_UPLOAD_CLIENT_CONFIG",
      prefix: "https://some-prefix.com/somethingelse/",
      headers: {
        header1: "header1value",
        header2: "header2value",
      },
    });
  }

  function closeModal() {
    sendMessage({
      type: "CLOSE_MODAL",
    });
  }

  function rerunScript() {
    sendMessage({
      type: "RERUN_SCRIPT",
    });
  }

  function stopScript() {
    sendMessage({
      type: "STOP_SCRIPT",
    });
  }

  function clearCache() {
    sendMessage({
      type: "CLEAR_CACHE",
    });
  }

  function sendThemeMessage() {
    sendMessage({
      type: "SET_CUSTOM_THEME_CONFIG",
      themeInfo: {
        primaryColor: "#1A6CE7",
        backgroundColor: "#FFFFFF",
        secondaryBackgroundColor: "#F5F5F5",
        textColor: "#1A1D21",
        // Option is deprecated, but we still test to ensure backwards compatibility:
        widgetBackgroundColor: "#FFFFFF",
        // Option is deprecated, but we still test to ensure backwards compatibility:
        widgetBorderColor: "#D3DAE8",
        // Option is deprecated, but we still test to ensure backwards compatibility:
        skeletonBackgroundColor: "#CCDDEE",
        font: 0,
        base: 0,
        bodyFont: '"Inter", "Source Sans", sans-serif',
        codeFont: '"Source Code", monospace',
        baseFontSize: 14,
        fontFaces: [
          {
            family: "Inter",
            url: "https://rsms.me/inter/font-files/Inter-Regular.woff2?v=3.19",
            weight: 400,
          },
          {
            family: "Inter",
            url: "https://rsms.me/inter/font-files/Inter-SemiBold.woff2?v=3.19",
            weight: 600,
          },
          {
            family: "Inter",
            url: "https://rsms.me/inter/font-files/Inter-Bold.woff2?v=3.19",
            weight: 700,
          },
        ],
        fontSizes: {
          tinyFontSize: 10,
          smallFontSize: 12,
          baseFontSize: 14,
        },
      },
    });
  }

  function sendDarkThemeMessage() {
    sendMessage({
      type: "SET_CUSTOM_THEME_CONFIG",
      themeInfo: {
        primaryColor : "#1ED760",
        backgroundColor : "#121212",
        secondaryBackgroundColor : "#333333",
        textColor : "#FFFFFF",
        linkColor : "#9D9D9D",
        borderColor : "#7F7F7F",
        widgetBackgroundColor: "#FFFFFF",
        widgetBorderColor: "#D3DAE8",
        skeletonBackgroundColor: "#CCDDEE",
        font: 0,
        base: 0,
        bodyFont: '"Inter", "Source Sans", sans-serif',
        codeFont: '"Source Code", monospace',
        baseFontSize: 14,
      },
    });
  }

  function restartWebsocketConnection() {
    sendMessage({
      type: "RESTART_WEBSOCKET_CONNECTION",
    });
  }

  function terminateWebsocketConnection() {
    sendMessage({
      type: "TERMINATE_WEBSOCKET_CONNECTION",
    });
  }

  function setInputsDisabled() {
    sendMessage({
      type: "SET_INPUTS_DISABLED",
      disabled: true,
    })
  }
</script>

<style>
  html {
    margin: 0;
    padding: 0;
    height: 100%;
  }

  body {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: absolute;
    margin: 0;
    padding: 0;
    inset: 0;
    background-image: linear-gradient(
      45deg,
      #fff4c9 25%,
      #ffffff 25%,
      #ffffff 50%,
      #fff4c9 50%,
      #fff4c9 75%,
      #ffffff 75%,
      #ffffff 100%
    );
    background-size: 56.57px 56.57px;
  }

  #toolbar {
    padding: 0.5rem 1rem;
    display: flex;
    flex-direction: row;
    gap: 1rem;
  }

  #guest {
    flex: 1;
    border: none;
  }
</style>

<div id="toolbar" data-testid="toolbar">
  This is the host frame.
  <button onclick="sendThemeMessage()">Send Theme</button>
  <button onclick="sendDarkThemeMessage()">Send Dark Theme</button>
  <button onclick="rerunScript()">Rerun Script</button>
  <button onclick="stopScript()">Stop Script</button>
  <button onclick="clearCache()">Clear Cache</button>
  <button onclick="closeModal()">Close modal</button>
  <button onclick="setHostMenuItem()">Add Menu Item</button>
  <button onclick="setHostToolbarItem()">Add Toolbar Item</button>
  <button onclick="setHideSidebarNav()">Hide Sidebar Nav</button>
  <button onclick="setSidebarDownshift()">Sidebar Chevron Downshift</button>
  <button onclick="setAuthToken()">Set Auth Token</button>
  <button onclick="setFileUploadClientConfig()">Set file upload config</button>
  <button onclick="restartWebsocketConnection()">Restart Websocket</button>
  <button onclick="terminateWebsocketConnection()">Terminate Websocket</button>
  <button onclick="setInputsDisabled()">Disable Inputs</button>
</div>

<!-- we replace $APP_URL during the playwright test with the correct one -->
<iframe name="guest" id="guest" src="$APP_URL" />
